import json

from django.views import View
from django.http import JsonResponse
from django.contrib.auth import login

from store import settings
from .models import OAuthQQUser
from apps.users.models import User
from apps.oauth.utils import generic_openid, check_access_token

from QQLoginTool.QQtool import OAuthQQ



# Create your views here.

class QQLoginURLView(View):

    def get(self, request):
        # 生成QQLoginTool实例对象
        # client_id=None,               appid
        # client_secret=None,           appsecret
        # redirect_uri=None,            用户同意登录之后，跳转的页面
        # state=None                    不知道什么意思，随便写。等出了问题再分析问题
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                     client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI,
                     state="xxxxx")

        # 调用对象方法生成跳转链接
        qq_login_url = qq.get_qq_url()

        # 返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'login_url': qq_login_url})


class OauthQQView(View):

    def get(self, request):

        # 获取code
        code = request.GET.get('code')

        if code is None:
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})

        # code换取token
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                     client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI,
                     state="xxxxx")
        token = qq.get_access_token(code)

        # token换取openid
        openid = qq.get_open_id(token)

        # 根据openid进行查询判断
        try:
            qquser = OAuthQQUser.objects.get(openid)
        except OAuthQQUser.DoesNotExist:
            # 未绑定 需绑定
            access_token = generic_openid(openid)
            response = JsonResponse({'code': 0, 'access_token': access_token})
            return response

        else:
            # 存在
            login(request, qquser.user)

            response = JsonResponse({'code': 0, 'errmsg': 'ok'})
            response.set_cookie('username', qquser.user.username)

            return response

    def post(self, request):

        data = json.loads(request.body.decode())

        password = data.get('password')
        mobile = data.get('mobile')
        sms_code = data.get('sms_code')
        access_token = data.get('access_token')

        # 解密 access_token
        openid = check_access_token(access_token)
        if openid is None:
            return JsonResponse({'code': 400, 'errmsg': '参数缺失'})

        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 手机号不存在
            user = User.objects.create_user(username=mobile, mobile=mobile, password=password)
        else:
            # 手机号存在
            if not user.check_password(password):
                return JsonResponse({'code': 400, 'errmsg': '账号或密码错误'})

        OAuthQQUser.objects.create(user=user, openid=openid)

        login(request, user)

        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.set_cookie('username', user.username)

        return response
